<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="编号名称" prop="idName">
        <el-input
          v-model="queryParams.idName"
          placeholder="请输入编号名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="处理人员" prop="handler">
        <el-input
          v-model="queryParams.handler"
          placeholder="请输入处理人员"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="请求日期" prop="requestDate">
        <el-date-picker clearable
          v-model="queryParams.requestDate"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择请求日期">
        </el-date-picker>

 

      </el-form-item>
      <el-form-item label="数据来源" prop="dataSource">
        <el-input
          v-model="queryParams.dataSource"
          placeholder="请输入数据来源"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="总额" prop="totalAmount">
        <el-input
          v-model="queryParams.totalAmount"
          placeholder="请输入总额"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="申请人" prop="applicant">
        <el-input
          v-model="queryParams.applicant"
          placeholder="请输入申请人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="申请时间" prop="applyTime">
        <el-date-picker clearable
          v-model="queryParams.applyTime"
          type="date"
            value-format="YYYY-MM-DD"
          placeholder="请选择申请时间">
        </el-date-picker>
      </el-form-item>
      <!-- <el-form-item label="出入库标识" prop="inOutIndicator">
        <el-input
          v-model="queryParams.inOutIndicator"
          placeholder="请输入出入库标识"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <!-- <el-form-item label="更新时间" prop="updatedAt">
        <el-date-picker clearable
          v-model="queryParams.updatedAt"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择更新时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="更新人" prop="updatedBy">
        <el-input
          v-model="queryParams.updatedBy"
          placeholder="请输入更新人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="更新人ID" prop="updatedById">
        <el-input
          v-model="queryParams.updatedById"
          placeholder="请输入更新人ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['scm:request:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['scm:request:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['scm:request:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['scm:request:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="requestList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="编号" align="center" prop="id" /> -->
      <el-table-column label="编号名称" align="center" prop="idName" />
      <el-table-column label="当前流程状态" align="center" prop="status">
        <template #default="scope">
          {{ scope.row.status === '1' || scope.row.status === 1 ? '已提交' : scope.row.status }}
        </template>
      </el-table-column>
      <el-table-column label="数据来源" align="center" prop="dataSource" />
      <el-table-column label="总额" align="center" prop="totalAmount" />
      <el-table-column label="申请人" align="center" prop="handler" />
      <el-table-column label="出入库标识" align="center" prop="inOutIndicator">
        <template #default="scope">
          {{ scope.row.inOutIndicator === '1' || scope.row.inOutIndicator === 1 ? '入库' : '出库' }}
        </template>
      </el-table-column>
      <el-table-column label="请求日期" align="center" prop="requestDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.requestDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>

   
      <!-- <el-table-column label="申请人" align="center" prop="applicant" /> -->
      <!-- <el-table-column label="申请时间" align="center" prop="applyTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.applyTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column> -->

      <!-- <el-table-column label="更新时间" align="center" prop="updatedAt" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updatedAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="更新人" align="center" prop="updatedBy" />
      <!-- <el-table-column label="更新人ID" align="center" prop="updatedById" /> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary"  icon="Edit" @click.stop="handleUpdate(scope.row)" v-hasPermi="['scm:request:edit']">编辑</el-button>
          <el-button link type="primary"  icon="Delete" @click.stop="handleDelete(scope.row)" v-hasPermi="['scm:request:remove']">删除</el-button> 
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加或修改出入库请求记录对话框 -->
    <el-dialog :title="title" 
      v-model="open" width="1200px" 
      :width="dialogMaximized ? '98vw' : '1200px'"
      :fullscreen="dialogMaximized"
      append-to-body>
      <template #title>
        <span>{{ title }}</span>
        <el-button
          @click="toggleDialogMax"
          style="float: right; margin-right: 0; border: none; background: none;"
          circle
          :title="dialogMaximized ? '还原' : '最大化'"
        >
          <el-icon>
            <component :is="dialogMaximized ? 'Minus' : 'FullScreen'" />
          </el-icon>
        </el-button>
     </template>

      <!-- 1. 标题栏 -->
      <div style="font-weight: bold; font-size: 22px; color: #222; text-align: center; margin-bottom: 24px;">
        产品入库
      </div>

      <!-- 产品入库登记描述区 -->
      <!-- <el-card shadow="never" style="margin-bottom: 18px;">
        <div style="font-size: 15px; color: #333;">
          <div>1、产品入库登记</div>
          <div>2、记录所有入库操作的商品</div>
          <div>3、所有入库操作的订单都在此记录，进行商品入库</div>
          <div style="color: #f56c6c; margin-top: 4px;">注：同一商品的辅助单位需保持一致</div>
        </div>
      </el-card> -->

      <!-- 人员/日期/入库信息组框 -->
      <el-card shadow="never" style="margin-bottom: 18px;">
        <el-form :inline="true" label-width="70px" style="margin-bottom: 10px;">
          
          <el-form-item label="入库人员" >
            <ScmUserInput
              v-model="form.handler"
              @select="handleUserSelect"
            />
          </el-form-item>

          <el-form-item label="入库日期" label-width="70px">
            <el-date-picker
              v-model="form.requestDate"
              type="date"
                value-format="YYYY-MM-DD"
              placeholder="请选择入库日期"
              style="width: 150px;"
            />
          </el-form-item>
         
          <el-form-item label="入库操作:" label-width="100px">
            <!-- <el-button type="primary" size="small" @click="showProductDialog = true">添加新行</el-button> -->
            <el-button type="primary" size="small" @click="showScmProductItemBySupplyOrderId = true">从供应商订单添加</el-button>
            <el-button type="primary"size="small"  @click="showImportDialog = true" style="margin-left: 10px;">从导入列表添加</el-button>
            <el-button type="success" size="small" @click="copyRow">复制</el-button>
            <el-button type="danger" size="small" @click="deleteRow">删除</el-button> 
          </el-form-item>
        </el-form>

        <!-- 入库信息表格 -->
        <el-table
          :data="inStockList"
          ref="inStockTable"
          border
          size="small"
          style="width: 100%; margin-bottom: 0;"
          height="320"
          :row-key="row => row.item_id"
          @selection-change="handleInStockSelectionChange"
        >
          <el-table-column type="selection" width="30" />
          <el-table-column label="供应商订单号" align="center" prop="mainOrderCode" />
          <el-table-column label="项目产品号" align="center" prop="projectProductId" />
          <!-- <el-table-column label="供应商报价单ID" align="center" prop="supplier_quote_id" />
          <el-table-column label="供应商名称" align="center" prop="supplier_name" />  -->
          <!-- <el-table-column label="出厂编号" align="center" prop="manufacture_number" />
          <el-table-column label="出厂子编号" align="center" prop="manufacture_sub_number" /> -->
          <el-table-column label="图号" align="center" prop="scmProjectProducts.drawingNumber" />
          <el-table-column label="版本" align="center" prop="scmProjectProducts.version" />
          <el-table-column label="品名" align="center" prop="scmProjectProducts.productName" />
          <el-table-column label="材质" align="center" prop="scmProjectProducts.material" />
          <!-- <el-table-column label="尺寸" align="center" prop="size" /> -->
          <el-table-column label="规格" align="center" prop="scmProjectProducts.specification" />
          <el-table-column label="颜色" align="center" prop="scmProjectProducts.color" />
          <el-table-column label="订单数量" align="center" prop="quantity" />
          <el-table-column label="单价"  align="center"  prop="unitPrice"/>
      
          <el-table-column label="已入库数量" align="center" prop="quantityInLib" />
          <el-table-column label="注残" align="center" prop="quantityNotInLib" >
            <template #default="scope">
              {{ (Number(scope.row.quantity) || 0) - (Number(scope.row.quantityInLib) || 0) }}
            </template> 
          </el-table-column>
              
          <el-table-column label="入库类型" align="center" prop="typeInLib"  width="120">
            <template #default="scope">
              <el-select v-model="scope.row.typeInLib" placeholder="请选择类型" style="width: 100px;">
                <el-option label="实际入库" value="1" />
                <el-option label="虚拟入库" value="2" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="入库数量" prop="quantityInThisTime" align="center" width="100">
            <template #default="scope">
              <el-input
                v-model="scope.row.quantityInThisTime"
                type="number"
                size="small"
                min="0"
                :max="(Number(scope.row.quantity) || 0) - (Number(scope.row.quantityInLib) || 0)"
                style="width: 80px;"
                @input="calcTotal(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="残次数量" align="center" prop="quantityInThisTimeHasIssue" >
            <template #default="scope">
              <el-input
                v-model="scope.row.quantityInThisTimeHasIssue"
                type="number"
                size="small"
                min="0"
                style="width: 80px;"
              />
            </template>
          </el-table-column>
          <!-- 仓库选择 -->
          <el-table-column label="仓库" width="160">
            <template #default="scope">
              <el-select
                v-model="scope.row.warehouse"
                placeholder="选择仓库"
                style="width: 120px;"
                @change="handleWarehouseChange(scope.row)"
              >
                <el-option
                  v-for="item in warehouseList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </template>
          </el-table-column>
          
          <!-- 库位选择 -->
          <el-table-column label="库位" width="160">
            <template #default="scope">
              <el-select
                v-model="scope.row.location"
                placeholder="选择库位"
                style="width: 120px;"
                :disabled="!scope.row.warehouse"
              >
                <el-option
                  v-for="loc in getLocationList(scope.row.warehouse)"
                  :key="loc.id"
                  :label="loc.locationName"
                  :value="loc.id"
                />
              </el-select>
            </template>
          </el-table-column>

       
 
        
          <el-table-column label="总价">
            <template #default="scope">
              <el-input v-model="scope.row.total" readonly />
            </template>
          </el-table-column>
        </el-table>




      </el-card>

      <!-- 其余内容保持现状 -->
      <!-- 3. 入库金额汇总区 -->
      <div style="display: flex; align-items: center; border-top: 1px solid #eee; padding: 16px 0 8px 0; margin-bottom: 16px;">
        <div style="flex: 1;">
          <span style="font-weight: bold;">成品入库总额：</span>
          <el-input v-model="inStockSummary.total" readonly style="width: 160px; margin-right: 24px;" />
      
        </div>
      </div>

      <!-- 4. 附件上传区 -->
      <div style="border-top: 1px solid #eee; padding: 12px 0 8px 0;">
        <span style="font-weight: bold;">入库相关附件上传：</span>
        <span v-if="!attachments.length" style="color: #aaa;">暂无内容</span>
       
        <el-upload
          v-model:file-list="attachments"
          action="/api/upload"           
          :auto-upload="false"
          :on-success="handleUploadSuccess"
          :on-error="handleUploadError"
          :on-remove="handleFileRemove"
          style="margin-left: 16px;"
          multiple
        >
            <el-button size="small" type="primary">选择文件</el-button>
            <el-button
              size="small"
              type="success"
              style="margin-left: 8px;"
              @click="startUpload"
              :disabled="!attachments.length || uploading"
            >开始上传</el-button>
        </el-upload>

        <div v-if="uploadStatus" style="margin-top: 8px; color: #409EFF;">
          {{ uploadStatus }}
        </div>
        <!-- 已上传文件列表 -->
        <el-table
          v-if="uploadedFiles.length"
          :data="uploadedFiles"
          style="margin-top: 12px; width: 400px;"
          size="small"
          border
        >
          <el-table-column label="文件名" prop="name" />
          <el-table-column label="状态" prop="status" width="80" />
          <el-table-column label="操作" width="80">
            <template #default="scope">
              <el-button
                type="danger"
                size="mini"
                @click="deleteUploadedFile(scope.$index)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>


        <!-- 5. 次品信息区 -->
      <div style="border-top: 1px solid #eee; padding: 12px 0 8px 0;">
        <span style="font-weight: bold;">残次相关信息：</span>
        <template v-if="hasDefective">
          <el-input
            v-model="defectiveRemark"
            type="textarea"
            placeholder="请输入残次说明"
            style="width: 400px; margin-left: 12px;"
            rows="2"
          />
        </template>
        <template v-else>
          <span style="color: #aaa;">暂无内容</span>
        </template>
      </div>

      <!-- 6. 操作按钮区 -->
      <div slot="footer" class="dialog-footer" style="text-align: right; border-top: 1px solid #eee; padding-top: 16px;">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="warning" style="background: orange; color: #fff; border: none;" @click="submitForm">提 交</el-button>
      </div>
    </el-dialog>
    <ScmProductList v-model="showProductDialog"  @select="handleProductSelect"/>
    <ScmProductItemBySupplyOrderId v-model="showScmProductItemBySupplyOrderId"  @select="handleScmProductItemBySupplyOrderIdSelect"/>
    <ScmProductItemImportDialog v-model="showImportDialog"  @select="handleImportSelect"/>
  </div>
</template>
  
<script>
import { listRequest, getRequest, delRequest, addRequest, updateRequest } from "@/api/scm/scmInventoryRequest";

import ScmProductList from "@/views/scm/inventoryRequestIn/ScmProductList.vue";
import ScmProductItemBySupplyOrderId from "@/views/scm/inventoryRequestIn/ScmProductItemBySupplyOrderId.vue";
import ScmProductItemImportDialog from "@/views/scm/inventoryRequestIn/ScmProductItemImportDialog.vue";

import ScmUserInput from "@/views/scm/commonModule/scmUserInput.vue";


import { listWarehouse } from "@/api/scm/warehouse";
import { listLocation } from "@/api/scm/location";
import { addLog } from "@/api/scm/scmInventoryLog";
import { id } from "element-plus/es/locales.mjs";

import { ElIcon } from 'element-plus'
import { FullScreen, Minus } from '@element-plus/icons-vue'
import { Edit, Delete } from '@element-plus/icons-vue'

export default {
  name: "Request",
  components: {  
    ElIcon,
    FullScreen,
    Minus,
    Edit, Delete,
    ScmProductList,
    ScmProductItemBySupplyOrderId,
    ScmUserInput,
    ScmProductItemImportDialog
 
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 出入库请求记录表格数据
      requestList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        idName: null,
        status: null,
        handler: null,
        requestDate: null,
        dataSource: null,
        totalAmount: null,
        applicant: null,
        applyTime: null,
        inOutIndicator: "1", // 默认入库
        updatedAt: null,
        updatedBy: null,
        updatedById: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        status: [
          { required: true, message: "当前流程状态不能为空", trigger: "change" }
        ],
        inOutIndicator: [
          { required: true, message: "出入库标识不能为空", trigger: "blur" }
        ],
      },
      
      // 入库信息表格数据
      inStockList: [],
      inStockSummary: {
        total: "",
        totalUpper: ''
      },
   
      showProductDialog: false,
      showScmProductItemBySupplyOrderId:false,
      inStockSelection: [],
      warehouseList: [],
      warehouseLocationMap: {}, // { warehouseId: [location, ...] }

      dialogMaximized: false,
   

      attachments: [],
      uploadedFiles: [], // { name, url, status }
      uploadStatus: '',
      uploading: false,

      defectiveRemark: '',

      showImportDialog: false,
    };
  },
  created() {
    this.getList();
    this.getWarehouseList();
  },
  computed: {
    hasDefective() {
      return this.inStockList.some(row => Number(row.quantityInThisTimeHasIssue) > 0);
      }
  },
  methods: {
    toggleDialogMax() {
      this.dialogMaximized = !this.dialogMaximized;
    },
    calcTotal(row) {
      row.total = (Number(row.quantityInThisTime) * Number(row.unitPrice)).toFixed(2);
      // 汇总
      let sum = this.inStockList.reduce((acc, cur) => {
        if (cur && typeof cur.total !== 'undefined') {
          return acc + Number(cur.total);
        }
        return acc;
      }, 0);
      this.inStockSummary.total = sum.toFixed(2);
      this.inStockSummary.totalUpper = this.digitUppercase(sum);
    },
    digitUppercase(n) {
      // 简单大写金额转换（可替换为更完整的实现）
      // ...实现略...
      return '柒仟柒佰陆拾柒元整';
    },

    /** 查询出入库请求记录列表 */
    getList() {
      this.loading = true;
      listRequest(this.queryParams).then(response => {
        this.requestList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        idName: null,
        status: null,
        handler: null,
        requestDate: null,
        dataSource: null,
        totalAmount: null,
        applicant: null,
        applyTime: null,
        inOutIndicator: null,
        updatedAt: null,
        updatedBy: null,
        updatedById: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.inStockList = []; // 清空入库明细
      this.title = "添加出入库请求记录";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getRequest(id).then(response => {
        this.form = response.data;
            // 关键：同步明细到表格
        this.inStockList = (response.data.scmInventoryLogList || []).map(item => ({
          id: item.id || "",
          orderId: item.orderId || "",
          mainOrderCode: item.orderCode || "",
          inventoryId: item.inventoryId || "",
          productId: item.productId || "",
          projectProductId: item.projectProductId || "",
          productName: item.productName || "",
          drawingVersion: item.drawingVersion || "",
          drawingNumberModel: item.drawingNumberModel || "",
          specification: item.specification || "",
          unit: item.unit || "",
          skuCode: item.skuCode || "",
          color: item.color || "",
          unitPrice: item.unitPrice || "",
          warehouse: item.warehouseId || "",
          location: item.warehouseLocationId || "",
          inventoryLogRequestId: item.inventoryLogRequestId || "",
          typeInLib: item.typeInLib ? String(item.typeInLib) : "1",
          changeType: item.changeType || "1",
          quantity:item.orderTotalQuantity || "",
          quantityInThisTime: item.changeQuantity || "", // 页面字段
          beforeQuantity: item.beforeQuantity || "",
          afterQuantity: item.afterQuantity || "",
          orderTotalQuantity: item.orderTotalQuantity || "",
          quantityInLib: item.orderQuantityInLib || "0",
          quantityNotInLib: item.orderQuantityNotInLib || "",
          quantityInThisTimeHasIssue: item.quantityInThisTimeHasIssue || "",
          BillStatus: item.BillStatus || "",
          BillDueDate: item.BillDueDate || "",
          BillDate: item.BillDate || "",
          BillComments: item.BillComments || "",
          BillRemarks: item.BillRemarks || "",
          createdAt: item.createdAt || this.form.requestDate || "",
          createdBy: item.createdBy || this.form.handler || "",
          createdById: item.createdById || "1",
           // 自动计算总价
          total: ((Number(item.changeQuantity || 0)) * (Number(item.unitPrice || 0))).toFixed(2)
         
         
          // 可根据实际字段补充其它映射
        }));
        
        // 汇总成品入库总额
        let sum = this.inStockList.reduce((acc, cur) => acc + Number(cur.total), 0);
        this.inStockSummary.total = sum.toFixed(2);
        // 可选：大写金额
        // this.inStockSummary.totalUpper = this.digitUppercase(sum);
        
        this.open = true;
        this.title = "修改出入库请求记录";
      });
    },


    /** 提交按钮 */
    submitForm() {
      // 1. 产品入库（入库人员）
      if (!this.form.handler) {
        this.$message.warning("请填写入库人员");
        return;
      }
      // 2. 入库日期
      if (!this.form.requestDate) {
        this.$message.warning("请填写入库日期");
        return;
      }
      // 3. 列表必填项校验
      let valid = true;
      for (const row of this.inStockList) {
        if (!row.typeInLib) {
          this.$message.warning("请填写每一行的入库类型");
          valid = false;
          break;
        }
        if (!row.quantityInThisTime) {
          this.$message.warning("请填写每一行的入库数量");
          valid = false;
          break;
        }
        if (typeof row.quantityInThisTimeHasIssue === 'undefined' || row.quantityInThisTimeHasIssue === null || row.quantityInThisTimeHasIssue === '') {
          this.$message.warning("请填写每一行的残次数量");
          valid = false;
          break;
        }
        if (!row.warehouse) {
          this.$message.warning("请填写每一行的仓库");
          valid = false;
          break;
        }
        if (!row.location) {
          this.$message.warning("请填写每一行的库位");
          valid = false;
          break;
        }
      }
      if (!valid) return;

      // 校验表格每一行
      let tableValid = true;
      for (const row of this.inStockList) {
        if (!row.scmProjectProducts.productName || !row.quantity || !row.warehouse) {
          tableValid = false;
          break;
        }
      }
      if (!tableValid) {
        this.$message.warning("请完善入库信息表格的必填项");
        return;
      }

      // 提交逻辑
      const payload = {
        // id: this.form.id,
        // idName: this.form.idName,
        status: "1",
        handler: this.form.handler,
        requestDate: this.form.requestDate,
        dataSource: "人员录入",
        totalAmount: this.inStockSummary.total || 0,
        applicant:  this.form.handler,
        applyTime: this.form.requestDate,
        inOutIndicator: "1",
        updatedAt: this.form.requestDate,
        updatedBy: this.form.handler,
        
        updatedById: "1",
        // 明细
        scmInventoryLogList: this.inStockList.map(item => ({

          id: item.id || "",
          orderId: item.orderId || "",
          orderCode: item.mainOrderCode || "",
          inventoryId: item.inventoryId || "",
          productId: item.productId || "",
          projectProductId: item.projectProductId || "",
          productName: item.productName || "",
          drawingVersion: item.drawingVersion || "",
          drawingNumberModel: item.drawingNumberModel || "",
          specification: item.specification || item.spec || "",
          unit: item.unit || item.massUnit || "",
          skuCode: item.skuCode || "",
          color: item.color || "",
          unitPrice: item.unitPrice || item.price || "",
          warehouseId: item.warehouse || item.warehouseId || "",
          warehouseLocationId: item.location || item.warehouseLocationId || "",
          inventoryLogRequestId: item.inventoryLogRequestId || "",
          typeInLib: item.typeInLib || "",
          changeType: item.changeType || "1",
          changeQuantity: item.changeQuantity || item.quantityInThisTime || "",
          beforeQuantity: item.beforeQuantity || "",
          afterQuantity: item.afterQuantity || "",
          orderTotalQuantity: item.orderTotalQuantity || "",
          orderQuantityInLib: item.orderQuantityInLib || item.quantityInLib || "",
          orderQuantityNotInLib: item.orderQuantityNotInLib || item.quantityNotInLib || "",
          quantityInThisTimeHasIssue: item.quantityInThisTimeHasIssue || "",
          BillStatus: item.BillStatus || "",
          BillDueDate: item.BillDueDate || "",
          BillDate: item.BillDate || "",
          BillComments: item.BillComments || "",
          BillRemarks: item.BillRemarks || "",
          createdAt: item.createdAt || this.form.requestDate || "",
          createdBy: item.createdBy || this.form.handler || "",
          createdById: item.createdById || "1"

        
        }))
    };
      if (this.form.id != null) {
        updateRequest(payload).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.open = false;
          this.getList();
        });
      } else {
        // 新增时，调用 addLog，把 inStockList 发送给后端
        console.log(payload);
        addRequest(payload).then(response => {
          this.$modal.msgSuccess("入库记录保存成功");
          this.open = false;
          this.getList();
        });
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除出入库请求记录编号为"' + ids + '"的数据项？').then(function() {
        return delRequest(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('scm/request/export', {
        ...this.queryParams
      }, `request_${new Date().getTime()}.xlsx`)
    },
    copyRow() {
      if (!this.inStockSelection.length) {
        this.$message.warning("请先选择要复制的行");
        return;
      }
      this.inStockSelection.forEach(row => {
        const newRow = { ...row };
        this.inStockList.push(newRow);
      });
      this.$message.success("复制成功");
    },
    deleteRow() {
      if (!this.inStockSelection.length) {
        this.$message.warning("请先选择要删除的行");
        return;
      }
      this.inStockList = this.inStockList.filter(row => !this.inStockSelection.includes(row));
      this.$message.success("删除成功");
      // 重新计算汇总
      let sum = this.inStockList.reduce((acc, cur) => acc + Number(cur.total), 0);
      this.inStockSummary.total = sum.toFixed(2);
      this.inStockSummary.totalUpper = this.digitUppercase(sum);
    },
      // ...其它...
    handleInStockSelectionChange(selection) {
      this.inStockSelection = selection;
    },
    handleScmProductItemBySupplyOrderIdSelect(selectedRows) {
      // 直接将选中的产品对象（原始属性）放入 inStockList，并补充仓库、库位、total 字段
      selectedRows.forEach(product => {
        this.inStockList.push({
          ...product,
          typeInLib: "1", // 默认实际入库
          warehouse: '',
          location: '',
          total: 0
        });
      });
      this.showScmProductItemBySupplyOrderId = false;
    },



    handleProductSelect(selectedRows) {
      // 将选中的产品添加到 inStockList
      selectedRows.forEach(product => {
        // 可根据实际字段映射
        this.inStockList.push({
          id: product.id,
          productProductId: product.productProductId,
          productName: product.productName,
          drawingNumber: product.drawingNumber,
          version: product.version,
          internalVersion: product.internalVersion,
          color: product.color,
          quantity: product.quantity,
          spec: product.model,
          massUnit: product.massUnit, // 可根据实际数据补充 
          price: product.massUnitPrice, // 可根据实际数据补充
          warehouse: '',
          location: '',
          total: 0
        });
      });
      this.showProductDialog = false;
    },
    // ...existing...
    async getWarehouseList() {
          // 获取仓库列表
          const warehouseRes = await listWarehouse();
          this.warehouseList = (warehouseRes.rows) ? warehouseRes.rows : [];

          // 获取库位列表
          const locationRes = await listLocation();
          const locations = ( locationRes.rows) ? locationRes.rows : [];

          // 构建仓库ID到库位的映射（以 location.warehouseId === warehouse.id 作为关联条件）
          this.warehouseLocationMap = {};
          this.warehouseList.forEach(warehouse => {
            this.warehouseLocationMap[warehouse.id] = locations.filter(loc => loc.warehouseId === warehouse.id);
          });
    },
    getLocationList(warehouseId) {
      return this.warehouseLocationMap[warehouseId] || [];
    },
    handleWarehouseChange(row) {
      // 清空库位
      row.location = '';
    },
    handleUserSelect(user) {
    // user 是选中的人员对象
    this.form.handler = user.value || user.userName || '';
    // 如需其它逻辑可补充
    },
    
    startUpload() {
      this.uploadStatus = '';
      this.uploading = true;
      this.$refs.upload.submit();
    },
    handleUploadSuccess(response, file, fileList) {
      this.uploadStatus = '上传成功';
      this.uploading = false;
      // 假设后端返回文件url
      this.uploadedFiles.push({
        name: file.name,
        url: response.url || '',
        status: '已上传'
      });
    },
    handleUploadError(err, file, fileList) {
      this.uploadStatus = '上传失败';
      this.uploading = false;
    },
    handleFileRemove(file, fileList) {
      // 只移除未上传的附件
      this.attachments = fileList;
    },
    deleteUploadedFile(index) {
      this.uploadedFiles.splice(index, 1);
    },

    handleImportSelect(selectedPlans) {
      const mapped = selectedPlans.map(item => {
        const unitPrice = Number(item.unitPrice || 0);
        const quantityInThisTime = Number(item.currentRequestInQuantity || 0);
        return {
          ...item,
          typeInLib: "1", // 固定值
          quantityInThisTime, // 映射
          quantityInThisTimeHasIssue: "0", // 固定值
          warehouse: item.warehouseId || "", // 下拉框绑定
          location: item.locationId || "",  // 下拉框绑定
          total: (unitPrice * quantityInThisTime).toFixed(2) // 计算总价
          // 其它 inStockList 需要的字段可以继续补充
        };
      });
      this.inStockList.push(...mapped);
      this.showImportDialog = false;
    }

  }
};
</script>


<style scoped>
.el-table th, .el-table td {
  padding: 2px 2px !important;
}
</style>